/**
 * refresh='true'初始化不加载数据
 * <plus-ui-select placeholder="操作人" option-name="customerId" service-name="RecorderService" service-method="creatorlist"
 select-key="code"
 select-value="message" ng-model="my" change-do="test" width="100px" checked-index="0"></plus-ui-select>

 */
define(['common/js/filter/boss-filter-0.1', 'common/lib/emailtip/jquery.emailtip.js'], function () {
    diretiveModule.directive('plusUiSelect', function ($injector) {
        return {
            restrict: "AE",
            scope: {
                ngModel: '=',
                changeDo: '&',
                optionCondition:'=',
                checkedKey:'=',
                ngDisabled:'='
            },
            replace: true,
            controller: function ($scope) {
                $scope.currentInputData = "";
            },
            template: function (elm, attrs) {
                var optionTip = attrs.placeholder ? attrs.placeholder : "";

                var selectValue = attrs.selectValue;
                var cutLength = attrs.cutLength;
                var strFilter = "";
                if (/^[0-9]*[1-9][0-9]*$/.test(cutLength)) {
                    strFilter = "|substring:" + cutLength;
                }

                var choiceHStr = "";
                if (attrs.choiceHeight) {
                    choiceHStr += "style='height:" + attrs.choiceHeight + ";overflow-y:scroll;'";
                }
                var refreshStr = "";

                if (attrs.refresh && attrs.refresh == "true") {
                    if(typeof attrs.refreshLoad=="string" && attrs.refreshLoad == "false"){
                        refreshStr = 'refresh-delay="0"';
                    }else{
                        refreshStr = 'refresh="refreshFn($select.search)" refresh-delay="200"';
                    }
                }

                var selectWidthStr = "300px";

                if (attrs.width) {
                    selectWidthStr = attrs.width;
                }
                var usModel = "option.selected";
                var usRepeat = "option";
                var usHtml = "option";
                var usFilter = "filter: $select.search";
                var usMatch = "$select.selected." + attrs.selectValue;
                var usDisabled=attrs.disabled;
                var template = '<div class="form-group">' + '<ui-select ng-disabled="'+usDisabled+'" ng-model="' + usModel + '" theme="bootstrap" style="width:' + selectWidthStr + '">' +
                    '<ui-select-match placeholder="' + optionTip + '">{{' + usMatch + '}}</ui-select-match>' +
                    '<ui-select-choices ' + refreshStr + ' repeat="' + usRepeat + ' in options | ' + usFilter + '" ' + choiceHStr + '>' +
                    '<span ng-bind-html="' + usHtml + '.' + attrs.selectValue + strFilter + ' | highlight: $select.search"></span>' +
                    '</ui-select-choices>' +
                    '</ui-select></div>';
                return template;
            },
            compile: function (tElm, tAttrs) {
                return {

                    post: function (scope, elm, attrs, ngmodel) {


                        ngmodel = ngmodel ? null : ngmodel;
                        var optionName = attrs.optionName;

                        scope.options = [];
                        scope.option = {};
                        scope.loadSelectionData = function (conditionObj,nowTimeData) {
                            //根据最新的条件获取数据
                            var condition = scope[attrs.optionCondition];

                            if (condition == null || condition == undefined) {
                                if (conditionObj != null && conditionObj != undefined) {
                                    condition = conditionObj;
                                } else {
                                    condition =scope.optionCondition;
                                }
                            }

                            var DataService = $injector.get(attrs.serviceName);
                            DataService[attrs.serviceMethod](condition).then(function (options) {
                                if(nowTimeData){
                                	if(scope.currentInputData && nowTimeData != scope.currentInputData){
                                        return;
                                    }
                                }
                                if (!options) {
                                    options = [];
                                }
                                scope.options.length = 0;
                                for (var index in options) {
                                    scope.options.push(options[index]);
                                }
                                //默认选择第几项
                                if (attrs.checkedIndex) {
                                    try {
                                        var checkedIndex = parseInt(attrs.checkedIndex);

                                        //如果是"==请选择=="项，略过
                                        if (scope.options.length == 0) {
                                            return;
                                        }

                                        if (checkedIndex >= scope.options.length) {
                                            console.error("out of range，默认选择项下标超过了下拉的长度");
                                            return;
                                        }
                                        scope.option.selected = scope.options[checkedIndex];
                                    } catch (e) {
                                        console.error("默认选择的项数必须为正整数");
                                    }
                                }
                                //默认选择key
                                if (scope.checkedKey) {
                                    try {

                                        if (scope.options.length == 0) {
                                            return;
                                        }
                                        angular.forEach(scope.options, function (item) {

                                            if (angular.equals(item[attrs.selectKey].toLowerCase(), scope.checkedKey.toLowerCase())) {
                                                scope.option.selected = item;
                                                return;
                                            }
                                        });

                                    } catch (e) {
                                        console.error(e);
                                    }
                                }
                            });


                        };


                        if (attrs.refresh && attrs.refresh == "true") {
                            scope.refreshFn = function (searchStr) {
                                if (!searchStr) return;
                                /*if (typeof attrs.refreshLoad=="string" && attrs.refreshLoad == "false") {
                                 return;
                                 }*/
                                scope.currentInputData = searchStr;
                                var conObj = {};
                                conObj[optionName] = searchStr;
                                scope.loadSelectionData(conObj,searchStr);
                            };
                        } else {
                            scope.loadSelectionData();
                        }
                        scope.$watch("option.selected", function (newVal, oldVal) {
                            if (newVal !== oldVal) {
                                if(typeof scope.ngModel=='string'){
                                    scope.ngModel =newVal[attrs.selectKey]
                                }else{
                                    scope.ngModel = newVal;
                                }

                                if (attrs.changeDo) {
                                    scope.changeDo({model:newVal});
                                }
                            }else{
                            	/**
                                 * 如果这个值不为空 且optimum有值则调用
                                 * 吕鹏加
                                 */
                                if(newVal && newVal.optimum && newVal.optimum == 1){
                                	scope.changeDo({model:newVal});
                                }
                            }
                            
                        }, true);
                        //清空监听
                        scope.$on("refresh-" + optionName, function (event, msg) {
                            if (!scope.options) return;

                            scope.option.selected = scope.options[0];
                        });
                        //监听列表选项更新事件
                        scope.$on("reload-" + optionName, function (event, conditionObj) {
                            //delete scope.ngModel;
                            delete scope.option.selected;
                            scope.loadSelectionData(conditionObj);
                        });

                    }
                };
            }
        };
    });
});